import { ref, reactive, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { channelApi } from '@/api'
import getMenus from './getMenus'
export default props => {     
    const router = useRouter()   
    const listRef = ref(null)
    const currentPage = ref(1)
    const totalPage = ref(0)
    const id = computed(() => props.id - 0)
    const childId = computed(() => props.subid - 0)
    const isChannelIndex = computed(() => id.value && !childId.value)
    // 获取频道下面的二级菜单
    const menus = computed(() => getMenus(id.value))
    const currentModules = reactive([])
    // 获取频道下面的模块
    const modules = computed(() => {
        const arr = []
        if (isChannelIndex.value) {            
            arr.push(...menus.value.map(menu => {
                const { title, tid } = menu
                return {
                    title: title === '推荐' ? '热门推荐' : title,
                    tid,
                    data: []
                }
            }))
        } else {
            arr.push(...[
                {
                    title: '热门推荐',
                    tid: childId.value,
                    data: []
                },
                {
                    title: '最新视频',
                    tid: childId.value,
                    data: []
                }
            ])
        }
        return arr
    })

    // 列表加载操作
    const stopLoading = () => {
        listRef.value?.stopLoad()
    }
    const startLoading = () => {
        listRef.value?.startLoad()
    }
    const complete = () => {
        listRef.value?.completeLoad()
    }

    // 页面初始化获取频道推荐数据
    const initRecommend = async () => {
        const initLoadTabs = menus.value.slice(0, 3)
        const results = initLoadTabs.map(async tab => {
            const response = await channelApi.getRecommend({
                rid: tab.tid
            })
            return response
        })

        // 按次序输出
        let newModules = []
        for (const [index, result] of results.entries()) {
            const res = await result
            let cm = {
                title: modules.value[index].title,
                tid: modules.value[index].tid,
                data: null
            }
            if (res) {
                const { code, data } = res
                if (code === 0 && data) {
                    cm.data = data.slice(0, 4)                    
                }
            } 
            newModules.push(cm)
        }

        currentModules.push(...newModules)
        currentPage.value = 2
        totalPage.value = menus.value.length
        stopLoading()
    }

    // 滚动加载更多发送请求
    const getRecommend = async (rid) => {
        try {
            const { data } = await channelApi.getRecommend({
                rid
            })
            if (Array.isArray(data)) {
                currentModules.push({
                    title: modules.value[currentPage.value].title,
                    tid: modules.value[currentPage.value].tid,
                    data: data.slice(0, 4)
                })

                if (currentPage.value === totalPage.value - 1) {
                    complete()
                }                
            }
        } catch (error) {
            console.log(error)           
        } finally {
            stopLoading()
        }
    }  

    // 页面初始化获取频道下面的其他子频道数据
    const initChannel = async () => {
        const results = modules.value.map(async (mod, index) => {
            let response = null
            if (index === 0) {
                response = await channelApi.getRecommend({
                    rid: props.subid
                })
            } else {
                response = await channelApi.getDynamic({
                    id: props.id,
                    rid: props.subid,
                    pn: currentPage.value
                })
            }
            return response
        })

        // 按次序输出
        let newModules = []
        totalPage.value = null
        for (const [index, result] of results.entries()) {
            const res = await result
            let cm = {
                title: modules.value[index].title,
                tid: modules.value[index].tid,
                data: null
            }
            if (res) {
                // 请求成功解析数据
                const { code, data } = res
                if (code !== 0) { 
                    continue
                }
                if (index === 0) {
                    if (Array.isArray(data)) {
                        cm.data = data.slice(0, 4)                    
                    }
                } else {
                    const { archives, page: { size, count } } = data
                    cm.data = archives
                    totalPage.value === null && (totalPage.value = Math.ceil(count / size))
                }                                              
            }
            newModules.push(cm)
        }
        currentModules.push(...newModules)        
        stopLoading()
    }

    // 滚动加载更多发送请求
    const getChannel = async () => {
        try {
            const { data } = await channelApi.getDynamic({
                id: props.id,
                rid: props.subid,
                pn: currentPage.value
            })  
            if (data) {
                const { archives, page: { count, size } } = data
                if (!totalPage.value) {
                    totalPage.value = Math.ceil(count / size)                   
                }
                archives.forEach(item => {
                    const { bvid } = item
                    const match = currentModules[1].data.find(item => item.bvid === bvid)
                    if (!match) {
                        currentModules[1].data.push(item)
                    }
                })

                if (currentPage.value === 4) {
                    complete()
                }
            }
        } catch (error) {
            console.log(error)          
        } finally {
            stopLoading()
        }
    }

    // 页面滚动到底部的加载事件
    const handleLoad = () => {
        const cpv = currentPage.value
        const tpv = totalPage.value
        if (cpv < tpv - 1) {
            const nextPage = cpv + 1
            currentPage.value = nextPage
            if (isChannelIndex.value) {
                getRecommend(modules.value[nextPage].tid)
            } else {
                if (modules.value[1].data !== null) {
                    getChannel()
                }
            }
        } else {
           complete()
        }
    }
    
    // 查看排行榜
    const handleRank = id => {        
        router.push({
            name: 'rank',
            params: {
                id
            }
        })        
    }
    // 查看二级频道
    const handleMore = subid => {
        router.push({
            name: 'channel',
            params: {
                id: props.id,
                subid
            }
        })
    }

    const initData = () => {
        startLoading()
        currentPage.value = 1
        totalPage.value = 0
        currentModules.splice(0, currentModules.length)
        if (isChannelIndex.value) {
            initRecommend()
        } else {
            initChannel()
        }
    }   

    watch(props, () => {                
        initData()
    }, {
        immediate: true
    })

    return {
        listRef,
        currentModules,
        handleLoad,
        handleRank,
        handleMore
    }
}